import datetime

from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin

from djangoProject3 import settings
from web import models


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        # 如果用户登录，在request中赋值
        user_id = request.session.get('user_id', 0)
        user_object = models.UserInfo.objects.filter(id=user_id).first()
        request.tracer = user_object
        # 获取当前用户访问的url
        # 检查url是否在白名单中，如果在则可以继续访问，如果不在则进行判断是否已登录
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        if not request.tracer:
            return redirect('web:login')
        # 获取当前用户所拥有的额度,在交易记录中获取
        # 获取当前用户最近的一次交易记录
        _object = models.Transaction.objects.filter(user=user_object).order_by('-id').first()
        # 判断是否已过期
        current_datetime = datetime.datetime.now()
        if _object.end_datetime and _object.end_datetime < current_datetime:
            _object = models.Transaction.objects.filter(user=user_object, status=2, price_policy__category=1).first()
        # request.transaction = _object
        request.price_policy = _object.price_policy

        # 免费额度存储配置文件
        # _object = models.Transaction.objects.filter(user=user_object).order_by('-id').first()
        # if not _object:
        #     # 没有购买
        #     request.price_policy = models.PricePolicy.objects.filter(category=1, title='个人免费版').first()
        # else:
        #     current_datetime = datetime.datetime.now()
        #     if _object.end_datetion and _object.end_datetime < current_datetime:
        #         _object = models.Transaction.objects.filter(user=user_object, status=2, price_policy__category=1).first()
        #     else:
        #         request.price_policy = _object.price_policy
